class ApplicationController < ActionController::API
  def prepare_query(base)
    #query
    cond = params.reject {|name| %w{controller action}.include?(name) || name.start_with?('_')}
    base = base.where(cond)

    # pagination
    range = params[:_range] || '1_'
    range = "1#{range}" if range.start_with?('_')
    range = range.split('_').collect { |e| e.to_i  }
    base = base.skip(range[0] - 1)
    base = base.limit(range[1] - range[0] + 1) if range.length > 1

    # sort
    sort = params[:_sort] || ''
    sort = sort.split(/\s*,\s*/)
    sort = sort.collect do |token|
      token = "+#{token}" unless token.start_with?('+', '-')
      mode = (token[0] == '+') ? :asc : :desc
      field = token[1..-1]
      [field, mode]
    end
    sort = sort.to_h
    base = base.order(sort)

    base
  end

  def respond(base)
    if params.include?('_count')
      render json: {count: base.count}
    else
      includes = params[:_embed] || ''
      includes = includes.split(/\s*,\s*/)
      hash = base.as_json(include: includes)
      render json: hash
    end
  end

  rescue_from Mongoid::Errors::Validations do
    render status: 400, plain: '资源验证错误' # TODO 缺失的验证错误消息
  end
end
